<?php

function reg_user()
{
    global $m;

    $user = $_POST['user'];
    $mail = $_POST['mail'];
    $pw = $_POST['pw'];
    $realname = $_POST['realname'];

    // TODO:检查
    $stmt = $m->get_stmt("INSERT INTO `w_user` (`name`, `mail`, `pw`, `realname`) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $user, $mail, $pw, $realname);

    $stmt->execute();
    $err = $stmt->error;
    $stmt->close();
    if (!$err) {
        redirect('index.php?mode=login&msg=' . urlencode("注册成功，赶紧登录吧"));
    } else {
        msg("注册失败: " . $err);
    }
}

function login_user()
{
    global $m;

    $login = $_POST['user'];
    $pw = $_POST['pw'];

    if (!isset($login)) {
        msg('请输入用户名');
    }
    if (!isset($pw)) {
        msg('请输入密码');
    }

    $sql = 'SELECT `id`, `pw` FROM `w_user` WHERE ';
    if (stripos($login, '@') !== FALSE) { // 含有@符号, 邮箱
        $sql .= '`mail`';
    } else {
        $sql .= '`name`';
    }
    $sql .= ' = ? AND `pw` = ?';

    $stmt = $m->get_stmt($sql);
    $stmt->bind_param('ss', $login, $pw);
    $stmt->execute();

    //绑定数据
    $stmt->bind_result($uid, $upw);
    //获取数据
    $stmt->fetch();

    $stmt->close();

    if (!$uid) {
        msg("用户不存在或密码错误");
    }

    // 登录成功
    setcookie("uid", $uid, time() + 999999);
    setcookie("pwd", pw_gen_cookie($upw), time() + 999999);

    msg('<meta http-equiv="refresh" content="1; url=index.php"> 登录成功, 正在跳转中。。。');
}

function check_user(bool $redirect_login = false)
{
    global $m;

    $cuid = $_COOKIE['uid'];

    $stmt = $m->get_stmt("SELECT `id`, `name`, `mail`, `pw`, `realname` FROM `w_user` WHERE `id` = ?");
    $stmt->bind_param('i', $cuid);
    $stmt->execute();

    $resm = $stmt->get_result(); // 获取结果

    $stmt->close();// 关闭stmt

    if ($resm->num_rows == 0) {
        clear_cookie();
        if ($redirect_login) {
            relogin();
        }
        return;
    }

    $row = $resm->fetch_array(); // 只有一行

    $upw = $row['pw'];

    $cpw = $_COOKIE['pwd'];
    if ($cpw != pw_gen_cookie($upw)) {
        clear_cookie();
        if ($redirect_login) {
            relogin();
        }
    }
    return $row;
}

function clear_cookie()
{
    setcookie("uid", '', time() - 3600);
    setcookie("pwd", '', time() - 3600);
}

function relogin($reason = '')
{

    redirect('index.php?mode=login&msg=' . urlencode($reason)); // 重新登录
}
